﻿Imports System.ServiceModel

Public Class Main
    'Private Const INTEGRATOR_ID As String = "2b3a8764-d586-4543-9b7e-8283443f219"
    Dim _random As Random
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _random = New Random()
    End Sub

    Private Sub testXMLButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles testXMLButton.Click

        Dim transactionID As Long = _random.[Next]()
        Dim token = [String].Empty
        Dim xml As String = String.Empty
        Dim Certificado As String = String.Empty
        Dim noCertificado As String = String.Empty

        resultTextBox.Text = ""
        barcodeQR.Image = Nothing

        Try
            Using securitySrv = New SrvSecurity.SeguridadClient()
                Dim serviceToken = securitySrv.ObtenerToken(Utilerias.RFC, transactionID)
                Dim toHash = [String].Format("{0}|{1}", Utilerias.Integrator_ID, serviceToken)
                token = Security.Hash(toHash)
            End Using

            transactionID = _random.[Next]()
            Dim invoiceXML = New SrvTimbrado.ComprobanteXML() With { _
             .DatosXML = "<?xml version=""1.0"" encoding=""utf-8""?><cfdi:Comprobante xmlns:cfdi=""http://www.sat.gob.mx/cfd/3"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" sello=""n/4ZBqQcVAL+S+tLpnTQneoShA4QJcJISwtQYpwO4qYH6Unh0fvLxAqLKqedIrqizOjdUu/0oDZprqISB//FHJpHz+Fj2NmdSEoAJmRXQyUTe9FpqvSApTG2CNIuq1WRDkGqgtcMP1emrWe7R60Bbn0djY6q/okjQk0ircxYm0Q="" certificado=""MIIFFTCCA/2gAwIBAgIUMjAwMDEwMDAwMDAxMDAwMDE3NDAwDQYJKoZIhvcNAQEFBQAwggFvMRgwFgYDVQQDDA9BLkMuIGRlIHBydWViYXMxLzAtBgNVBAoMJlNlcnZpY2lvIGRlIEFkbWluaXN0cmFjacOzbiBUcmlidXRhcmlhMTgwNgYDVQQLDC9BZG1pbmlzdHJhY2nDs24gZGUgU2VndXJpZGFkIGRlIGxhIEluZm9ybWFjacOzbjEpMCcG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1UdIAQJMAcwBQYDKgMEMBMGA1UdJQQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4IBAQAYTO7pSfCJmkzX1GVmZGDUcZqte9dPaiiukfKt7sY95NEs16x8z+1z6w9VKjEy1EAs2asYpyWgDj/HfZtufjxb/HfgaXz6NwawjF4BEJOtTM13B7babamZruG9RWIO/XG4ntx/6jeji7bL+cX2ISOf4SCbRAPdwaumn5dTsrIEB6fI5JSCP5YgRfXMH5RYVw/3ltSUMi0jqv1LVjScqRtd9xnC4asbX4vfg1aTXY42MHTvOoRvc7JskqI7gb7JSLO1QXpUGU8Upp54sDLN5sjrCNV8PVB3REC5v7x0Oy/u1VrFGantW84aY4sPTBZ+xzhZ9tozgm4FAO3X4k5Kl8wP"" fecha=""2012-01-12T11:28:35"" version=""3.2"" xsi:schemaLocation=""http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd"" serie=""A"" folio=""1564"" formaDePago=""Pago en una sola Exhibición"" noCertificado=""20001000000100005867"" condicionesDePago=""Contado"" subTotal=""101.00"" TipoCambio=""1.00"" Moneda=""MXN"" total=""117.16"" metodoDePago=""Efectivo"" tipoDeComprobante=""ingreso"" NumCtaPago=""123456789"" LugarExpedicion=""manzanillo"">    <cfdi:Emisor rfc=""AAA010101AAA"" nombre=""Sulplas S.A. de C.V."">        <cfdi:DomicilioFiscal calle=""Cerro de atenquique"" noExterior=""978"" colonia=""Las Aguilas"" localidad=""Zapopan"" referencia=""Las aguilas"" municipio=""ZAPOPAN"" estado=""Jalisco"" pais=""Mexico"" codigoPostal=""45509"" />        <cfdi:RegimenFiscal Regimen=""honorarios"" />    </cfdi:Emisor>    <cfdi:Receptor rfc=""P&amp;AA901017AAA"" nombre=""P&amp;AA901017AAA"" />    <cfdi:Conceptos>        <cfdi:Concepto cantidad=""10"" unidad=""pza"" descripcion=""paquete"" valorUnitario=""10.10"" importe=""101.00"" />    </cfdi:Conceptos>    <cfdi:Impuestos totalImpuestosTrasladados=""16.16"">        <cfdi:Traslados>            <cfdi:Traslado impuesto=""IVA"" tasa=""16.00"" importe=""16.16"" />        </cfdi:Traslados>    </cfdi:Impuestos>    <cfdi:Complemento>           </cfdi:Complemento></cfdi:Comprobante>"
            }
            Dim cfdi As Comprobante = New Comprobante()
            cfdi = GeneradorSello.Deserialization(cfdi, GetType(Comprobante), invoiceXML.DatosXML)

            cfdi.fecha = Date.Now
            invoiceXML.DatosXML = GeneradorSello.Serialize32(cfdi, GetType(Comprobante))

            cfdi.sello = GeneradorSello.stampInvoice(invoiceXML.DatosXML, Certificado, noCertificado)
            cfdi.certificado = Certificado
            cfdi.noCertificado = noCertificado

            invoiceXML.DatosXML = GeneradorSello.Serialize32(cfdi, GetType(Comprobante))

            Using invoiceSrv = New SrvTimbrado.TimbradoClient()
                Dim advertencias = invoiceSrv.TimbraXML(invoiceXML, Utilerias.RFC, token, transactionID)
                resultTextBox.Text = invoiceXML.DatosXML
            End Using

            transactionID = _random.[Next]()
            Dim doc As New XDocument()
            doc = XDocument.Parse(invoiceXML.DatosXML)
            Dim singature As New XElement("{http://www.sat.gob.mx/TimbreFiscalDigital}TimbreFiscalDigital")
            Dim uuid As String = doc.Root.Descendants(singature.Name).ToArray()(0).Attribute("UUID").Value
            Using repositorySrv = New SrvRepository.RepositorioClient()
                Dim infoQR = repositorySrv.ObtenerQR(Utilerias.RFC, token, transactionID, uuid)
                Dim ms = New System.IO.MemoryStream(infoQR.Imagen)
                barcodeQR.Image = New System.Drawing.Bitmap(ms)

            End Using

        Catch serviceFault As FaultException(Of SrvSecurity.FallaServicio)
            Using errorForm = New frmError(TranslateFault.ToServiceError(serviceFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch sessionFauld As FaultException(Of SrvSecurity.FallaSesion)
            ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail))
        Catch serviceFault As FaultException(Of SrvInvoices.FallaServicio)
            Using errorForm = New frmError(TranslateFault.ToServiceError(serviceFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch sessionFauld As FaultException(Of SrvInvoices.FallaSesion)
            ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail))
        Catch validationFault As FaultException(Of SrvInvoices.FallaValidacion)
            Using errorForm = New frmError(TranslateFault.ToValidationError(validationFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch ex As Exception
            ShowUnknownError(ex.Message)
        End Try
    End Sub

    Private Sub ShowSessionError(ByVal sessionError As Entity.SessionError)
        MessageBox.Show(String.Format("Status {0}: {1}", sessionError.Status.ToString(), sessionError.Description), "Ecodex UniTest")
    End Sub

    Private Sub ShowUnknownError(ByVal p1 As String)
        MessageBox.Show(String.Format("Error: {0}", p1), "Ecodex UniTest")
    End Sub

    Private Sub btnXMLStamp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXMLStamp.Click
        Using formFiles = New frmXMLStamp()
            formFiles.ShowDialog()
        End Using
    End Sub

    Private Sub btnGetToken_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetToken.Click
        Using formToken = New frmToken()
            formToken.ShowDialog()
        End Using
    End Sub

    Private Sub btnGetStatusStamp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetStatusStamp.Click
        Using formGetStatusStamp = New frmGetStatusStamp()
            formGetStatusStamp.ShowDialog()
        End Using
    End Sub

    Private Sub btnGetStatusClient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetStatusClient.Click
        Using formGetStatusClient = New frmGetStatusClient()
            formGetStatusClient.ShowDialog()
        End Using
    End Sub

    Private Sub btnGetStamp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetStamp.Click
        Using formGetStamp = New frmGetStamp()
            formGetStamp.ShowDialog()
        End Using
    End Sub

    Private Sub btnAsignarTimbres_Click(sender As System.Object, e As System.EventArgs) Handles btnAsignarTimbres.Click
        Using formAsignarTimbres = New frmAsignarTimbresEmisor
            formAsignarTimbres.ShowDialog()
        End Using
    End Sub

    Private Sub btnAltaEmisor_Click(sender As System.Object, e As System.EventArgs) Handles btnAltaEmisor.Click
        Using formAltaEmisor = New frmAltaEmisor
            formAltaEmisor.ShowDialog()
        End Using
    End Sub

    Private Sub btnCancelaMultiple_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelaMultiple.Click
        Using formCancelaMultiple = New frmCancelaMultiple
            formCancelaMultiple.ShowDialog()
        End Using
    End Sub

    Private Sub btnCancelaOtros_Click(sender As System.Object, e As System.EventArgs) Handles btnCancelaOtros.Click
        Using formCancelaOtros = New frmCancelaOtros
            formCancelaOtros.ShowDialog()
        End Using
    End Sub

    Private Sub btnRecuperaAcuse_Click(sender As System.Object, e As System.EventArgs) Handles btnRecuperaAcuse.Click
        Using formRecuperaAcuse = New frmRecuperaAcuseCancelacion
            formRecuperaAcuse.ShowDialog()
        End Using
    End Sub

    Private Sub btnDocuments_Click(sender As System.Object, e As System.EventArgs) Handles btnGetDocuments.Click
        Using formGetDocuments = New frmGetDocuments
            formGetDocuments.ShowDialog()
        End Using
    End Sub

    Private Sub btnUniTestXMLRetencion_Click(sender As System.Object, e As System.EventArgs) Handles btnUniTestXMLRetencion.Click
        Dim transactionID As Long = _random.[Next]()
        Dim token = [String].Empty
        Dim xml As String = String.Empty
        Dim Certificado As String = String.Empty
        Dim noCertificado As String = String.Empty

        resultTextBox.Text = ""
        barcodeQR.Image = Nothing

        Try
            Using securitySrv = New SrvSecurity.SeguridadClient()
                Dim serviceToken = securitySrv.ObtenerToken(Utilerias.RFC, transactionID)
                Dim toHash = [String].Format("{0}|{1}", Utilerias.Integrator_ID, serviceToken)
                token = Security.Hash(toHash)
            End Using

            transactionID = _random.[Next]()
            Dim invoiceXML = New SrvTimbrado.ComprobanteXML() With { _
             .DatosXML = "<?xml version=""1.0"" encoding=""UTF-8""?> <retenciones:Retenciones xmlns:retenciones=""http://www.sat.gob.mx/esquemas/retencionpago/1""     xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""     xmlns:dividendos=""http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos""     xsi:schemaLocation=""     http://www.sat.gob.mx/esquemas/retencionpago/1     http://www.sat.gob.mx/esquemas/retencionpago/1/retencionpagov1.xsd     http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos     http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos/dividendos.xsd""     Version=""1.0""     Sello=""by/AKeq4+4XqBtGD0FZ3tK47aSRPqAEXvg4T/9ttTT9ZjGHFYP8BuA/YA+gq7eC2itGSVa6KgZW+N9iw6m5zFb7vGIXQcRAT6qKSeNen261uXk8r3FICaKjo3QuR6414Uh1VsckauCDo8axXRLnYThL7HCrRvV918YSsNuXJW/4=""     NumCert=""20001000000100005867""     Cert=""MIIEdDCCA1ygAwIBAgIUMjAwMDEwMDAwMDAxMDAwMDU4NjcwDQYJKoZIhvcNAQEFBQAwggFvMRgwFgYDVQQDDA9BLkMuIGRlIHBydWViYXMxLzAtBgNVBAoMJlNlcnZpY2lvIGRlIEFkbWluaXN0cmFjacOzbiBUcmlidXRhcmlhMTgwNgYDVQQLDC9BZG1pbmlzdHJhY2nDs24gZGUgU2VndXJpZGFkIGRlIGxhIEluZm9ybWFjacOzbjEpMCcGCSqGSIb3DQEJARYaYXNpc25ldEBwcnVlYmFzLnNhdC5nb2IubXgxJjAkBgNVBAkMHUF2LiBIaWRhbGdvIDc3LCBDb2wuIEd1ZXJyZXJvMQ4wDAYDVQQRDAUwNjMwMDELMAkGA1UEBhMCTVgxGTAXBgNVBAgMEERpc3RyaXRvIEZlZGVyYWwxEjAQBgNVBAcMCUNveW9hY8OhbjEVMBMGA1UELRMMU0FUOTcwNzAxTk4zMTIwMAYJKoZIhvcNAQkCDCNSZXNwb25zYWJsZTogSMOpY3RvciBPcm5lbGFzIEFyY2lnYTAeFw0xMjA3MjcxNzAyMDBaFw0xNjA3MjcxNzAyMDBaMIHbMSkwJwYDVQQDEyBBQ0NFTSBTRVJWSUNJT1MgRU1QUkVTQVJJQUxFUyBTQzEpMCcGA1UEKRMgQUNDRU0gU0VSVklDSU9TIEVNUFJFU0FSSUFMRVMgU0MxKTAnBgNVBAoTIEFDQ0VNIFNFUlZJQ0lPUyBFTVBSRVNBUklBTEVTIFNDMSUwIwYDVQQtExxBQUEwMTAxMDFBQUEgLyBIRUdUNzYxMDAzNFMyMR4wHAYDVQQFExUgLyBIRUdUNzYxMDAzTURGUk5OMDkxETAPBgNVBAsTCFVuaWRhZCAxMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2TTQSPONBOVxpXv9wLYo8jezBrb34i/tLx8jGdtyy27BcesOav2c1NS/Gdv10u9SkWtwdy34uRAVe7H0a3VMRLHAkvp2qMCHaZc4T8k47Jtb9wrOEh/XFS8LgT4y5OQYo6civfXXdlvxWU/gdM/e6I2lg6FGorP8H4GPAJ/qCNwIDAQABox0wGzAMBgNVHRMBAf8EAjAAMAsGA1UdDwQEAwIGwDANBgkqhkiG9w0BAQUFAAOCAQEATxMecTpMbdhSHo6KVUg4QVF4Op2IBhiMaOrtrXBdJgzGotUFcJgdBCMjtTZXSlq1S4DG1jr8p4NzQlzxsdTxaB8nSKJ4KEMgIT7E62xRUj15jI49qFz7f2uMttZLNThipunsN/NF1XtvESMTDwQFvas/Ugig6qwEfSZc0MDxMpKLEkEePmQwtZD+zXFSMVa6hmOu4M+FzGiRXbj4YJXn9Myjd8xbL/c+9UIcrYoZskxDvMxc6/6M3rNNDY3OFhBK+V/sPMzWWGt8S1yjmtPfXgFs1t65AZ2hcTwTAuHrKwDatJ1ZPfa482ZBROAAX1waz7WwXp0gso7sDCm2/yUVww==""     CveRetenc=""01"" FechaExp=""2015-01-27T11:40:00-06:00"">     <retenciones:Emisor RFCEmisor=""AAA010101AAA"" NomDenRazSocE=""Prueba""/>     <retenciones:Receptor Nacionalidad=""Nacional"">         <retenciones:Nacional RFCRecep=""CROW100623S70"" NomDenRazSocR=""CROW JAPAN""/>     </retenciones:Receptor>     <retenciones:Periodo MesIni=""10"" MesFin=""11"" Ejerc=""2014""/>     <retenciones:Totales montoTotOperacion=""0.000000"" montoTotGrav=""0.000000""         montoTotExent=""0.000000"" montoTotRet=""0.000000"">         <retenciones:ImpRetenidos montoRet=""0.000000"" TipoPagoRet=""Pago definitivo""/>         <retenciones:ImpRetenidos montoRet=""0.000000"" TipoPagoRet=""Pago definitivo""/>     </retenciones:Totales>     <retenciones:Complemento>         <dividendos:Dividendos Version=""1.0"">             <dividendos:DividOUtil CveTipDivOUtil=""06"" MontISRAcredRetMexico=""10"" MontISRAcredRetExtranjero=""10"" TipoSocDistrDiv=""Sociedad Nacional"" MontDivAcumExt=""1.000000"" MontDivAcumNal=""1.000000"" MontISRAcredNal=""1.00000"" MontRetExtDivExt=""1.000000""/>             <dividendos:Remanente ProporcionRem=""10""/>         </dividendos:Dividendos>     </retenciones:Complemento> </retenciones:Retenciones>"
            }
            Dim retencion As Retenciones = New Retenciones()
            retencion = GeneradorSello.Deserialization(retencion, GetType(Retenciones), invoiceXML.DatosXML)

            retencion.FechaExp = Date.Now.ToString("yyyy-MM-ddThh:mm:sszzz")
            invoiceXML.DatosXML = GeneradorSello.SerializeRetencion(retencion, GetType(Retenciones))

            retencion.Sello = GeneradorSello.stampInvoice(invoiceXML.DatosXML, Certificado, noCertificado)
            retencion.Cert = Certificado
            retencion.NumCert = noCertificado

            invoiceXML.DatosXML = GeneradorSello.SerializeRetencion(retencion, GetType(Retenciones))

            Using invoiceSrv = New SrvTimbrado.TimbradoClient()
                Dim advertencias = invoiceSrv.TimbraXML(invoiceXML, Utilerias.RFC, token, transactionID)
                resultTextBox.Text = invoiceXML.DatosXML
            End Using

            transactionID = _random.[Next]()
            Dim doc As New XDocument()
            doc = XDocument.Parse(invoiceXML.DatosXML)
            Dim singature As New XElement("{http://www.sat.gob.mx/TimbreFiscalDigital}TimbreFiscalDigital")
            Dim uuid As String = doc.Root.Descendants(singature.Name).ToArray()(0).Attribute("UUID").Value

        Catch serviceFault As FaultException(Of SrvSecurity.FallaServicio)
            Using errorForm = New frmError(TranslateFault.ToServiceError(serviceFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch sessionFauld As FaultException(Of SrvSecurity.FallaSesion)
            ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail))
        Catch serviceFault As FaultException(Of SrvInvoices.FallaServicio)
            Using errorForm = New frmError(TranslateFault.ToServiceError(serviceFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch sessionFauld As FaultException(Of SrvInvoices.FallaSesion)
            ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail))
        Catch validationFault As FaultException(Of SrvInvoices.FallaValidacion)
            Using errorForm = New frmError(TranslateFault.ToValidationError(validationFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch ex As Exception
            ShowUnknownError(ex.Message)
        End Try
    End Sub

    Private Sub btnGetDocument_Click(sender As System.Object, e As System.EventArgs) Handles btnGetDocument.Click
        Using formGetDocument = New frmGetDocument
            formGetDocument.ShowDialog()
        End Using
    End Sub

    Private Sub btnGetCertificateKey_Click(sender As System.Object, e As System.EventArgs) Handles btnGetCertificateKey.Click
        Using formGetCertificateKey = New frmGetCertificateKey
            formGetCertificateKey.ShowDialog()
        End Using
    End Sub

    Private Sub btnDeleteDocument_Click(sender As System.Object, e As System.EventArgs) Handles btnDeleteDocument.Click
        Using formDeleteDocument = New frmDeleteDocument
            formDeleteDocument.ShowDialog()
        End Using
    End Sub
End Class
